package com.simoniu.statement.statementdemo;

import com.simoniu.util.DBUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

public class StatementSqlInjectDemo {

    public boolean usersLogin(String username,String password){
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        String sql = "select * from users where username='"+username+"' and password = '"+password+"';";

        try{
            conn = DBUtil.getConnection();
            if(conn!=null){
                stmt = conn.createStatement();
                rs = stmt.executeQuery(sql);
                if(rs.next()){
                    return true;
                }
                return false;
            }
            return false;
        }catch(Exception ex){
            ex.printStackTrace();
            return false;
        }finally{
            try {
                if (rs != null) {
                    rs.close();
                    rs = null;
                }
                if (stmt != null) {
                    stmt.close();
                    stmt = null;
                }
                if (conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }


    public static void main(String[] args) throws Exception {

        String username = "admin";
        //产生了SQL注入
        String password = "123456' or '1=1";

        StatementSqlInjectDemo demo = new StatementSqlInjectDemo();
        if(demo.usersLogin(username,password)){
            System.out.println("登录成功!");
        }else{
            System.out.println("登录失败!");
        }

    }
}
